package com.ruoyi.common.core.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.RandomUtils;

import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.List;

public class CommonUtils {

	public static String getRevision(String revision) {
		if (StringUtils.isEmpty(revision))
			return "0";
		Integer version = Integer.valueOf(revision);
		version++;
		return version.toString();
	}

	public static String getSkuCode() {
		Snowflake snowflake = IdUtil.getSnowflake(getWorkId(), 1L);
		String id = snowflake.nextIdStr();
		return "PB" + id;
	}

	public static String getSkuCodeByPrefix(String prefix) {
		Snowflake snowflake = IdUtil.getSnowflake(getWorkId(), 1L);
		String id = snowflake.nextIdStr();
		return prefix + id;
	}

	private static Long getWorkId() {
		try {
			String hostAddress = Inet4Address.getLocalHost().getHostAddress();
			int[] ints = StringUtils.toCodePoints(hostAddress);
			int sums = 0;
			for (int b : ints) {
				sums = sums + b;
			}
			return (long) (sums % 32);
		} catch (Exception e) {
			// 失败就随机
			return RandomUtils.nextLong(0, 31);
		}
	}

	public static void main(String[] args) {
		System.out.println(getSkuCode());
	}

	public static <T> List<List<T>> averageAssign(List<T> source, int splitItemNum) {
		List<List<T>> result = new ArrayList<List<T>>();

		if (source != null && source.size() > 0 && splitItemNum > 0) {
			if (source.size() <= splitItemNum) {
				// 源List元素数量小于等于目标分组数量
				result.add(source);
			} else {
				// 计算拆分后list数量
				int splitNum = (source.size() % splitItemNum == 0) ? (source.size() / splitItemNum)
						: (source.size() / splitItemNum + 1);

				List<T> value = null;
				for (int i = 0; i < splitNum; i++) {
					if (i < splitNum - 1) {
						value = source.subList(i * splitItemNum, (i + 1) * splitItemNum);
					} else {
						// 最后一组
						value = source.subList(i * splitItemNum, source.size());
					}
					result.add(value);
				}
			}
		}
		return result;
	}
}
